<?php

class Message extends Node
{

    static public $user_id;
    protected $project;
    protected $destination;
    protected $parent_message;
    protected $owner;
    protected $iamowner;
    protected $replicable;
    protected $replys;
    protected $when;
    protected $duration;
    protected $content;
    protected $files;
    protected $opended = false;

    function __construct()
    {
        if ( empty( self::$user_id ) )
                self::$user_id = User::getLogged()->getId();
        $this->iamowner = ($this->owner == self::$user_id);
    }

    function setOpened( $open )
    {
        $this->opended = $open;
    }

    function handleGET( Event $e )
    {
        if ( $e->tag == 'switch_opened' ) {
            $this->_setOpened( !$this->opended );
            $e->cancelBubble();
        }
    }

    function fill()
    {
        if ( $this->opended ) {
            $datos = array( );
            Node::getArray( 'messages', $datos, 'parent_message=' . $this->id,
                    array( 'when' => 1 ) );
            foreach ( $datos as $d ) $this->appendChild( $d );
        }
    }

    function doPOST( Event $e )
    {
        if ( $e->tag == 'delete' ) {

            if ( $e->source->id == $this->id ) $this->delete();
            else $e->cancelBubble();
        }
        else if ( $e->tag == 'switch_replicable' ) {
            $this->switch_replicable();
            $e->cancelBubble();
        }
    }

    function delete()
    {
        if ( $this->iamowner ) {
            //OJO TENGO QUE BORRAR ESTE Y LOS HIJOS Y LOS HIJOS DE LOS HIJOS

            $sql = 'DELETE FROM messages WHERE id=' . $this->id;
            MyLink::$default->execute( $sql );
        }
    }

    function switch_replicable()
    {
        if ( $this->iamowner ) {
            $sql = 'UPDATE messages SET replicable=\'' . (($this->replicable == 'S') ? 'N' : 'S') . '\' WHERE id=' . $this->id;
            MyLink::$default->execute( $sql );
        }
    }

}

?>